package com.demo.servlet.demo1208;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        //对 count 属性 进行初始化
        config.getServletContext().setAttribute("count", 1);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setStatus(302);
        resp.sendError(404);

        resp.setContentType("text/html;charset=UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //模拟登陆
        if ("admin".equals(username) && "123".equals(password)) {
            //取出 count 值
            Integer count = (Integer) req.getServletContext().getAttribute("count");
            //更新登陆次数 + 1
            req.getServletContext().setAttribute("count", count + 1);
            //登录成功
            resp.getWriter().write("<h1>登录成功,这是您第" + count + "次登录！</h1>");
        } else {
            //登录失败
            resp.getWriter().write("<h1>登录失败</h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
